import sys

from PyQt6.QtWidgets import QApplication, QWidget, QFormLayout, QLabel, QLineEdit


class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)
        # 开启 Drop 功能
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        # Drag 事件：只对包含文本的拖拽事件生效
        if event.mimeData().hasText():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        # Drop 事件：接受拖拽入的文本
        self.setText(event.mimeData().text())


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle('Drag & Drop 测试')

        layout = QFormLayout()
        layout.addRow(QLabel('选择文本拖拽到文本框'))
        self.le1 = MyLineEdit(self)
        self.le1.setDragEnabled(True)
        self.le2 = MyLineEdit(self)
        layout.addRow(QLabel('文本框1：'), self.le1)
        layout.addRow(QLabel('文本框2：'), self.le2)
        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
